<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/11
 * Time: 10:30
 */

namespace Modules\Api\Service;

use HiCommon\Model\DiscoverApprise;
use HiCommon\Repository\DiscoverRepository;
use HiCommon\Repository\DiscoverAppriseRepository;
use HiCommon\Repository\DiscoverZanRepository;
use HiCommon\Repository\UsersLevelRepository;
use HiCommon\Repository\UsersRepository;

class DiscoverService extends BaseService
{

    /**
     *  获取朋友圈数据
     *  hinq 2019 11 12
     *  朋友圈的内容都是由后端发表 ， 前端用户只能查看和评论
     **/
    public function get_list( array $arr_input ){
        try{
            $arr_option['order'] = ['key'=>'created_at','value'=>'desc'];
            $arr_option['where'] = ['status'=>1,'issue'=>1];
            $arr_option['field'] = ['id','author_id','title','img','look_num','pid','type'];
            $arr_option['with'] = ['admin'];
            $arr_list = DiscoverRepository::get_list( (array) $arr_option , (array) $arr_input );
            $arr_list = $arr_list->toArray();
            foreach ( $arr_list['data'] as &$item ){
                $item['username'] = $item['admin']['username'];     //发表者的名称
                $item['pid'] = $item['pid']['id'];          //朋友圈（保养信息）类型
                $item['img'] = $item['img']['full_src'];              //图片
                //释放多余的字段
                unset($item['admin']);
                unset($item['author_id']);
                unset($item['type']);
                unset($item['pid']);
            }
            return list_page_data_for_api( $arr_list );
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *	验证表单数据
     *	hinq 2019 10 28
     *
     **/
    public function checkdata( array $arr_input ){

        if( empty( $arr_input['title'] ) ){
            return ['state'=>1,'msg'=>'标题不能为空','data'=>[],'error'=>''];
        }
        if( empty( $arr_input['content'] ) ){
            return ['state'=>1,'msg'=>'内容不能为空','data'=>[],'error'=>''];
        }
        preg_match_all('/<img.*?src="(.*?)".*?>/is',$arr_input['content'],$imgs);

        if( count( $imgs[1] ) == 0 ){
            return ['state'=>1,'msg'=>'请上传图片','data'=>[],'error'=>''];
        }else{
            $arr_input['img'] = $imgs[1][0];
        }
        if( empty( $arr_input['pid'] ) ){
            return ['state'=>1,'msg'=>'请选择类型','data'=>[],'error'=>''];
        }
        return $arr_input;
    }


    /**
     *  添加发布朋友圈信息
     *  hinq 2019 11 11
     *
     **/
    public function store( array $arr_input ){
        try{
            //验证数据的有效性
            $temp = self::checkdata( (array) $arr_input );
            if( $temp['state'] == 1 ){
                return $temp;
            }
            $user_id = api_user_id();

            //发布限制【同一个用户5秒内只能发布一条数据】
            $store_time = redis_string_get($user_id.'_store_time');
            if( !empty( $store_time  ) ){
                return hello_error('操作太频繁，请稍后在试');
            }
            //保存数据
            $data['author_id'] = $user_id;
            $data['title'] = $temp['title'];   //朋友圈标题
            $data['img'] = $temp['img'];        //朋友去图片
            $data['content'] = $temp['content'];    //朋友圈的内容
            $data['look_num'] = '0';        //阅读量
            $data['status'] = 1;
            $data['type'] = 1;
            $data['pid'] = $temp['pid'];
            $res = DiscoverRepository::add_one( (array) $data );
            if (empty($res)) {
                return hello_error('发布失败');
            }
            //redis记录上传发布的时间
            redis_string_set($user_id.'_store_time',time(),5,0);
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取指定的朋友圈数据（可以查看别人的数据）
     *  hinq 2019 11 11
     *
     **/
    public function detail( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            // 获取朋友圈数据
            $arr_optionp['with'] = ['user'];
            $arr_info = DiscoverRepository::get_one( (int) $nId , (array) $arr_optionp );
            if( empty( $arr_info->first() ) ){
                return hello_error('参数错误');
            }
            $arr_info = $arr_info->toArray();
            //统计当前指定数据评论的数量（这里需要优化）
            $where = ['discover_id'=>$nId,'lever'=>1,'status'=>1];
            $arr_info['apprise_num'] = DiscoverAppriseRepository::get_count_by_where( (array) $where );
            //统计当前指定数据点赞的数量（这里需要优化）
            unset( $where );
            $where = ['link_id'=>$nId , 'type'=>1];
            $arr_info['zan_num'] = DiscoverZanRepository::get_count_by_where( (array) $where );

            $arr_info['user']['level'] = '青铜会员';
            //获取VIP会员等级
            $level = UsersLevelRepository::get_all();
            foreach ($level as $k => $val) {
                //通过用户的积分获取用户的会员等级
                if( $arr_info['user']['integral_all'] >= $val['min_integral'] && $arr_info['user']['integral_all'] <= $val['max_integral'] ){
                    $arr_info['user']['level'] = $val['name'];
                }
            }
            $time = strtotime( $arr_info['created_at']);
            $arr_info['creatr_at_msg'] = friendly_date( $time ,'mohu' );  //模糊转换发布时间

            self::increase_num( (int) $nId ); //给当前朋友圈数据添加阅读量
            return hello_success('ok',$arr_info);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  修改发现（朋友圈）的阅读量和修改未读评论的状态
     *  hinq 2019 11 11
     *  查看一次详情 添加一次阅读量 不做任何限制
     **/
    public function apprise_change(int $nId ){
        \DB::beginTransaction();
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            //给朋友圈数据添加阅读量
            $res = DiscoverRepository::increase_num( $nId , 'look_num');
            //修改评论状态为已读
            $where = ['discover_id'=>$nId];
            $res2 = DiscoverAppriseRepository::change_state_to_where( (array) $where , 'is_read',1);
            if( $res && $res2 ){
                \DB::commit();
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            \DB::rollBack();
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  给朋友圈添加阅读量
     *  hinq 2019 11 25
     *
     **/
    public function increase_num( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            //如果有限制条件写这里【例如同一个用户、同一的客户的3分钟只算一次】

            //给朋友圈数据添加阅读量(没有限制条件，只要点击一次就算一次阅读量)
            $res = DiscoverRepository::increase_num( $nId , 'look_num');
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取指定的朋友圈的评论
     *  hinq 2019 11 11
     *
     **/
    public function apprise_list( int $nId )
    {
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $arr_option['where'] = ['discover_id'=>$nId , 'lever'=>1,'status'=>1];
            $arr_option['with'] = ['to_user','to_user.user_vehicle'=>function( $query ){
                $query->select('id','user_id','plate_no','brand_model');
            }]; //关联获取用户信息   用户的默认车辆型号信息
            $arr_option['withCount'] = ['zan','is_zan'];
            $arr_option['field'] = ['id','discover_id','content','user_id','is_read','status','created_at'];
            $arr_list = DiscoverAppriseRepository::get_list( (array) $arr_option );
            $arr_list = $arr_list->toArray();

            foreach ( $arr_list['data'] as &$item ){
                $item['created_at_msg'] = friendly_date( strtotime( $item['created_at']) ,'mohu' );  //友好的模糊转换发布时间
                $item['nickname'] = $item['to_user']['nickname'];
                $item['head_img'] = $item['to_user']['head_img']['full_src'];
                $item['nickname'] = $item['to_user']['nickname'];
                unset( $item['to_user'] );
                $item['car_id'] = empty($item['user_vehicle']['id'])? '' : $item['user_vehicle']['id'];
                $item['plate_no'] = empty($item['user_vehicle']['plate_no'])? '' : $item['user_vehicle']['plate_no'];
                $item['brand_model'] = empty($item['user_vehicle']['brand_model'])? '' : $item['user_vehicle']['brand_model'];
                unset( $item['user_vehicle'] );
                $item['is_zan'] = $item['is_zan_count'] == 0 ? 'false' : true;
                unset( $item['is_zan_count'] );
            }
            $arr_list =  list_page_data_for_api( $arr_list );
            return hello_success('ok',$arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  给指定的朋友圈、评论点赞
     *  hinq 2019 11 11
     *  type    类型  1：朋友圈  2：评论
     *  link_id   关联表的主键id
     **/
    public function zan( array $arr_input ){
        try{
            $user_id = api_user_id();
            $data['type'] = $arr_input['type'];
            $data['link_id'] = $arr_input['id'];
            //检测是否有数据
            $data['user_id'] = $user_id;
            $count = DiscoverZanRepository::get_count_by_where( (array) $data );
            if( $count == 0 ){  //添加点赞
                $res = DiscoverZanRepository::add_one( (array) $data );
            }else{  //取消点赞
                $res = DiscoverZanRepository::delete_one_where( (array) $data );
            }
            if( empty( $res ) ){
                return hello_error('操作失败');
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  删除指定的评论数据
     *  hinq 2019 11 11
     *
     **/
    public function apprise_delete( int $nId ){
         try{
             $user_id = api_user_id();
             //验证是否是当前用户的数据
             $where = ['id'=>$nId,'user_id'=>$user_id];
             $count = DiscoverAppriseRepository::get_count_by_where( (array) $where );

             if( $count == 0 ){  //不是自己的数据  不可以删除
                return hello_error('参数错误');
             }
             $res = DiscoverAppriseRepository::delete_one_where( (array) $where );
             if( empty( $res ) ){
                 return hello_error('删除失败');
             }
             return hello_success('ok');
         }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
         }
    }

    /**
     *  添加朋友圈的评论数据
     *  hinq 2019 11 11
     *  朋友圈现在评论： 同一个用户+同一条数据在1分钟内只能评论一次
     **/
    public function apprise_store(array $arr_input ){
        try{
            $user_id = api_user_id();
            $str = 'fabiao_'.$user_id.'_'.$arr_input['id'];
            if( !empty( redis_string_get( $str ) ) ){
                return hello_error('操作频发，请稍后重试');
            }
            $data['discover_id'] = $arr_input['id'];
            $data['lever'] = 1;
            $data['content'] = $arr_input['content'];
            $data['user_id'] = $user_id;
            $data['status'] = 1;
            $data['is_read'] = 2;   // 是否已读  1：已读   2：未读
            $res = DiscoverAppriseRepository::add_one( (array) $data );
            if( empty( $res ) ){
                return hello_error('添加失败');
            }
            //1分钟只能评论一次
            redis_string_set( $str , 1, 60 );
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  发现（朋友圈）=》我的详细
     *  hinq 2019 11 11
     *
     **/
    public function my_info(){
        try{
            $user_id = api_user_id();
            $arr_option['field'] = ['username','head_img'];
            $info = UsersRepository::get_one( (int) $user_id , (array) $arr_option );
            //统计指定用户的评论
            $where = ['user_id'=>$user_id , 'lever'=>1,'status'=>1];
            $apprise_count = DiscoverAppriseRepository::get_count_by_where( (array) $where );
            //统计指定用户的点赞
            $map = ['user_id' => $user_id ];
            $zan_count = DiscoverZanRepository::get_count_by_where( (array) $map );
            //统计指定用户发布的数据
            $arr_map = ['author_id'=>$user_id];
            $send_count = DiscoverRepository::get_count_by_where( (array) $arr_map );

            $data['info'] = $info;
            $data['apprise_count'] = $apprise_count;
            $data['zan_count'] = $zan_count;
            $data['send_count'] = $send_count;
            return hello_success('ok',$data);
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  发现（朋友圈）-》我的-》我的评论
     *  hinq 2019 11 12
     *
     **/
    public function my_apprise()
    {
        try{
            $user_id = api_user_id();
            $arr_option['where'] = ['lever'=>1,'user_id'=>$user_id];
            $arr_option['with'] = ['discover','discover.user','discover.admin'];
            $arr_option['order'] = ['key'=>'created_at','value'=>'desc'];
            $arr_list = DiscoverAppriseRepository::get_list( (array) $arr_option );
            $arr_list = $arr_list->toArray();
            foreach ( $arr_list['data'] as &$item ){
                if( $item['discover']['type']['id'] == 1 ){
                    $item['discover']['username'] = $item['discover']['user']['nickname'];
                }else{
                    $item['discover']['user_info'] = $item['discover']['admin']['username'];
                }
                unset($item['discover']['user']);
                unset($item['discover']['admin']);
            }
            return list_page_data_for_api( $arr_list );
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  发现（朋友圈）-》我的-》我的点赞
     *  hinq 2019 11 12
     *
     **/
    public function my_zan()
    {
        try{
            $user_id = api_user_id();
            $arr_option['where'] = ['user_id'=>$user_id];
            $arr_option['with'] = ['discover','discover.user','discover.admin','discover_apprise','discover_apprise.discover','discover_apprise.discover.user','discover_apprise.discover.admin'];
            $arr_option['order'] = ['key'=>'created_at','value'=>'desc'];
            $arr_option['field'] = ['id','user_id','link_id','type'];
            $arr_list = DiscoverZanRepository::get_list( (array) $arr_option );
            $arr_list = $arr_list->toArray();
            foreach ( $arr_list['data'] as &$item ){
                $temp = [];
                if( $item['type'] == 2 ){   //点赞评论
                    $temp['img'] = $item['discover_apprise']['discover']['img']['full_src'];
                    $temp['title'] = $item['discover_apprise']['discover']['title'];
                    $temp['look_num'] = $item['discover_apprise']['discover']['look_num'];
                    $temp['type'] = $item['discover_apprise']['discover']['type'];
                    $temp['apprise'] = $item['discover_apprise']['content'];
                    if( $item['discover_apprise']['discover']['type']['id'] == 1 ){
                        $temp['username'] = $item['discover_apprise']['discover']['user']['nickname'];
                    }else{
                        $temp['username'] = $item['discover_apprise']['discover']['admin']['username'];
                    }
                    $item['data'] = $temp;
                }else{          //点赞朋友圈
                    $temp['img'] = $item['discover']['img']['full_src'];
                    $temp['title'] = $item['discover']['title'];
                    $temp['look_num'] = $item['discover']['look_num'];
                    $temp['type'] = $item['discover']['type'];
                    if( $item['discover']['type']['id'] == 1 ){
                        $temp['username'] = $item['discover']['user']['nickname'];
                    }else{
                        $temp['username'] = $item['discover']['admin']['username'];
                    }
                    $item['data'] = $temp;
                }
                unset( $item['discover']);
                unset( $item['discover_apprise']);
            }
            return list_page_data_for_api( $arr_list );
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  发现（朋友圈）-》我的-》我的发布（朋友圈）
     *  hinq 2019 11 12
     *
     **/
    public function my_list()
    {
        try{
            $user_id = api_user_id();
            $arr_option['where'] = ['type'=>1,'author_id'=>$user_id,'status'=>1];
            $arr_option['field'] = ['id','title','img','look_num','created_at'];
            $arr_option['withCount'] = ['is_read'];   //统计是否有未读的评论  大于1位有未读评论 否则没有
            $arr_list = DiscoverRepository::get_list( (array) $arr_option );
            $arr_list = $arr_list->toArray();
            return list_page_data_for_api( $arr_list );
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  发现（朋友圈）-》我的-》我的发布（朋友圈）->删除
     *  hinq 2019 11 12
     *
     **/
    public function delete( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $user_id = api_user_id();
            //验证当前数据是否有效
            $where = ['id'=>$nId , 'author_id'=>$user_id,'status'=>1];
            $count = DiscoverRepository::get_count_by_where( (array) $where );
            if( $count == 0 ){
                return hello_error('您没有权限删除');
            }
            $res = DiscoverRepository::delete_one((int) $nId);
            if( empty( $res ) ){
                return hello_error('删除失败');
            }
            return hello_error('删除成功');
        }catch ( \Exception $exception){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


}